import argparse
import multiprocessing
from contextlib import asynccontextmanager
from typing import Optional

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles
from xbase_util.common_util import check_path
from xbase_util.es_db_util import EsDb
from xbase_util.geo_util import GeoUtil
from base.TaskQueue import TaskQueue
from base.TaskThreadManager import TaskThreadManager
from base.util.redis_util import RedisUtil
from capture_api.automation.template_api import templateRouter
from capture_api.config_api import configRouter
from capture_api.current_config_api import currentConfigRouter
from capture_api.flow_api import flowRouter
from capture_api.web_api.web_api import webRouter
from global_ver import global_base_config, global_geoutil, req
import pydevd_pycharm

parser = argparse.ArgumentParser(description="参数")
parser.add_argument('--debug', action='store_true', help='是否用调试模式')
args = parser.parse_args()
if args.debug:
    pydevd_pycharm.settrace('10.255.76.63', port=9991, stdoutToServer=True, stderrToServer=True)
    print("调试模式已启用")
else:
    print("正常运行模式")


class AppState:
    threadManager: TaskThreadManager
    base_config: None
    redisUtil: Optional[RedisUtil] = None
    geoUtil: Optional[GeoUtil] = None
    esdb: Optional[EsDb] = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    from global_ver import out_folder
    check_path(out_folder)
    app.state = AppState()
    app.state.base_config = global_base_config
    app.state.threadManager = TaskThreadManager()

    app.state.redisUtil = RedisUtil(app.state.base_config)
    app.state.geoUtil = global_geoutil
    app.state.esdb = EsDb(req, multiprocessing.Manager())

    app.state.taskQueue = TaskQueue()
    app.state.redisUtil.remove_status("xcapture_status")
    yield
    app.state.taskQueue.stop_queue()
    app.state.threadManager.stop_manager()


app = FastAPI(lifespan=lifespan)
app.include_router(webRouter, prefix="/v1")
app.include_router(templateRouter, prefix="/auto")
app.include_router(currentConfigRouter, prefix="/current_config")
app.include_router(configRouter, prefix="/config")
app.include_router(flowRouter, prefix="/flow")
app.mount("/", StaticFiles(directory="web"))
if __name__ == '__main__':
    app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"],
                       allow_headers=["*"])
    uvicorn.run(app, host="0.0.0.0", port=9090)
